/* Console example — App opening commands

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <inttypes.h>
#include "esp_log.h"
#include "esp_console.h"
#include "argtable3/argtable3.h"
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "esp_err.h"
#include "cmd_open.h"
#include "func_ui.h"

static const char *TAG = "cmd_open";

static struct {
    struct arg_str *app_name;
    struct arg_end *end;
} open_args;

/*
 * 调用此函数退出当前功能UI，返回主界面    
*/
void exit_current_func_ui(void);

static int open_app_func(int argc, char **argv)
{
    int nerrors = arg_parse(argc, argv, (void **)&open_args);
    if (nerrors != 0) {
        arg_print_errors(stderr, open_args.end, argv[0]);
        return 1;
    }

    const char *app_name = open_args.app_name->sval[0];
    ESP_LOGI(TAG, "Opening app: %s", app_name);

    exit_current_func_ui();

    func_list_t func_type = FUNC_MAX;
    if (strcmp(app_name, "logic") == 0) {
        func_type = FUNC_LOGIC_ANALYZER;
    } else if (strcmp(app_name, "bilibili") == 0) {
        func_type = FUNC_BILIBILI;
    } else if (strcmp(app_name, "setting") == 0) {
        func_type = FUNC_SYSTEM_SETTINGS;
    } else if (strcmp(app_name, "video") == 0) {
        func_type = FUNC_VIDEO_PLAYER;
    } else if (strcmp(app_name, "music") == 0) {
        func_type = FUNC_MUSIC_PLAYER;
    } else {
        ESP_LOGE(TAG, "Unknown app: %s", app_name);
        printf("Available apps: logic, bilibili, setting, video, music\n");
        return 1;
    }

    load_func_ui(func_type);
    return 0;
}

/**
 * 注册open命令到控制台系统
 * 
 * 该命令用于打开指定的应用程序
 * 用法: open <app_name>
 * 可用应用: logic, bilibili, setting, video, music
 */
void register_open(void)
{
    // 定义命令参数
    open_args.app_name = arg_str1(NULL, NULL, "<app_name>", "应用名称");
    open_args.end = arg_end(1);

    // 配置命令结构体
    const esp_console_cmd_t open_cmd = {
        .command = "open",
        .help = "打开指定的APP\n"
                "用法: open <app_name>\n"
                "可用应用: logic, bilibili, setting, video, music\n"
                "示例:\n"
                "  open logic     # 打开逻辑分析仪功能\n"
                "  open music     # 打开音乐播放功能",
        .hint = NULL,
        .func = &open_app_func,
        .argtable = &open_args,

    };

    // 注册命令到控制台系统
    esp_err_t err = esp_console_cmd_register(&open_cmd);
    if (err != ESP_OK) {
        ESP_LOGE(TAG, "Failed to register 'open' command: %s", esp_err_to_name(err));
    } else {
        ESP_LOGI(TAG, "'open' command registered successfully");
    }
}